# -*- coding: utf-8 -*-

import zmail
from queue import Queue, Empty
import time
from threading import Thread, Lock
import logging
import datetime
from functools import wraps


def singleton(cls):
    instances = {}

    @wraps(cls)
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return get_instance


_logger = logging.getLogger(__name__)


@singleton
class Mail(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.queue = Queue()
        self.lock = Lock()
        server = zmail.server('87558708@qq.com', 'zdvncxdtnomfcade')
        # 这是 发件箱

        if server.smtp_able():
            pass
            # SMTP function.
        if server.pop_able():
            pass
            # POP function.
        self.server = server

    def lockedstart(self):
        with self.lock:
            if not self.isAlive():
                self.daemon = True
                self.start()

    def send(self, email, code):
        self.lockedstart()
        self.queue.put((email, code))

    def _send_code(self, email, code):
        mail = {
            # 这是邮件内容
            'subject': 'TheWell register code',
            'content_text': 'TheWell register code is: ' + code
        }

        self.server.send_mail(
            [email],
            # 这是 收件箱
            mail
        )

    def run(self):
        while True:
            try:
                print(datetime.datetime.now(), 'run, 1, ')
                email, code = self.queue.get(True)
                print(datetime.datetime.now(), 'run, 2, ', email, code)
                self._send_code(email, code)
                print(datetime.datetime.now(), 'run, 3,  ok', email, code)
                pass
            except Exception as e:
                _logger.error('Error: %s' % str(e))


if __name__ == '__main__':
    pass

    # mail = {
    #     # 这是邮件内容
    #     'subject':'通过程序发送邮件 测试!',
    #     'content_text':'这封邮件是用程序给你发过去的, 你能看到他, 就是程序 ok 了'
    # }

    # server.send_mail(
    #     ['winboy99@163.com', '85557644@qq.com'],
    #     # 这是 收件箱
    #     mail )
